package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MedicineBankDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Medicine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service(interfaceClass = MedicineBankService.class)
@Transactional
public class MedicineBankServiceImpl implements MedicineBankService {
    @Autowired
    private MedicineBankDao medicineBankDao;


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面

        Page<Medicine> page = medicineBankDao.findByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Medicine medicine) {
        medicineBankDao.add(medicine);
    }

    @Override
    public void addAll(List<Medicine> list) {
        if(list != null && list.size() > 0){
            for (Medicine medicine : list) {
                //判断当前日期是否已经进行了设置
                long count = medicineBankDao.findCountByOrderDate(medicine.getName());
                if(count > 0){
                    //如果已经设置，执行更新操作
                    medicineBankDao.editNumberByOrderDate(medicine);
                }else{
                    //如果没有设置，执行插入操作
                    medicineBankDao.add(medicine);
                }
            }
        }
    }
}
